package com.test.hello;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.example.dto.TopDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TopListener extends AnalysisEventListener<TopDTO> {

    private final int BATCH_COUNT = 3;
    List<TopDTO> list = new ArrayList<>();

    @Override
    public void invoke(TopDTO data, AnalysisContext analysisContext) {
        System.out.println("invoke---开始解析表格数据");
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            System.out.println("invoke---超过设定值，导入数据库");
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }
    @Override
    public void doAfterAllAnalysed (AnalysisContext analysisContext){
        System.out.println("doAfterAllAnalysed---开始处理");
        if(list.size()==0){
            return;
        }
        saveData();
        System.out.println("所有数据解析完成！");

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        super.invokeHeadMap(headMap, context);
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        super.invokeHead(headMap, context);
    }

    private void saveData() {
        System.out.println("list = " + list.size());
    }
}
